<?php

namespace Admin\Pages;

/**
 * Description of Index
 *
 * @author nofear
 */
class Login extends Page {

    private $URLManager;
    
    public function __construct() {
        parent::__construct();
        $this->URLManager = \Shared\URLManager::getInstance();
    }
    
    public function index() {
        $this->view = new \System\Template('@admin/login.twig');
        $this->view->username = "Admin";
        $Session = $this->getSession();
        
        if ($Session->have('message')) {
            $this->view->message = $Session->getMessage();
            $Session->removeMessage();
        }
    }

    public function check() {
        $request = $this->getRequest();
        $email = $request->get('email');
        $password = $request->get('password');

        if ($email && $password) {
            $email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);
            $password = filter_var(trim($password), FILTER_SANITIZE_STRING);

            $User = $this->EntityManager->getRepository('Shared\Main\Administrator')->findOneBy(array('email' => $email, 'password' => md5($password)));

            if ($User) {
                $_SESSION['user'] = $User;
                $path = isset($_SESSION['requestURL']) && $_SESSION['requestURL'] ? $_SESSION['requestURL'] : $this->URLManager->createPath('admin_home');
                unset($_SESSION['requestURL']);
                $this->redirect($path);
            }

//        $Administrator = new \Shared\Main\Administrator();
//        $Administrator->setEmail('admin@site.com');
//        $Administrator->setPassword(md5('admin'));
//        $Administrator->setUsername('Административен Профил');
//        $Administrator->setSecret('dasn9dsha9sdhsd0dajs-dk1w0cnj!U(B');
//        $Administrator->setIsActive(true);
//        $Administrator->setIsDeleted(false);
//        
//        $this->EntityManager->persist($Administrator);
//        $this->EntityManager->flush();
        }
        $message['text'] = 'Wrong email or password!';
        $message['type'] = 'alert-danger';
        
        $Session = $this->getSession();
        $Session->setMessage($message);
        $this->redirect($this->URLManager->createPath('admin_login'));
    }

    public function logout() {
        unset($_SESSION['user']);

        $this->redirect($this->URLManager->createPath('admin_login'));
    }

}
